package com.rc.saas.tenant.controller.elec;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.QrCodeUtils;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.area.PlatformProvince;
import com.rc.saas.tenant.model.elec.ElecGun;
import com.rc.saas.tenant.model.elec.ElecPile;
import com.rc.saas.tenant.model.hlht.HlhtTenantOpenfor;
import com.rc.saas.tenant.model.operator.RcOperator;
import com.rc.saas.tenant.model.operator.RcOperatorExample;
import com.rc.saas.tenant.model.tenant.TenantCompanyInfo;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.elec.ElecGunSearch;
import com.rc.saas.tenant.service.area.PlatformAreaService;
import com.rc.saas.tenant.service.elec.ElecGunService;
import com.rc.saas.tenant.service.elec.ElecPileService;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.service.hlht.HlhtTenantOpenforService;
import com.rc.saas.tenant.service.operator.RcOperatorService;
import com.rc.saas.tenant.service.tenant.TenantCompanyInfoService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.elec.ElecStationAndCityName;
import groovy.lang.Lazy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * zhoushiyu
 * 站标签
 */
@Controller
@RequestMapping("/elecGun")
public class ElecGunController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(ElecGunController.class);


    @Autowired
    private TenantCompanyInfoService tenantCompanyInfoService;

    @Autowired
    @Lazy
    private ElecPileService elecPileService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private RcOperatorService operatorService;

    @Autowired
    private PlatformAreaService areaService;

    @Autowired
    private HlhtTenantOpenforService hlhtTenantOpenforService;

    @Autowired
    private TenantRoleService tenantRoleService;

    @Autowired
    private RcOperatorService rcOperatorService;


    /**
     * 跳转站标签页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String elecStationPage(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<TenantCompanyInfo> tenantCompanyInfos = tenantCompanyInfoService.listByTenantCode(user.getTenantCode());
        model.addAttribute("tenantCompanyInfos", tenantCompanyInfos);
        return "/templates/elec/elecGun";
    }

    @RequestMapping(value = "/temp1", method = RequestMethod.GET)
    public String temp1(Model model) {
        return "/templates/elec/temp1";
    }

    @RequestMapping(value = "/temp2", method = RequestMethod.GET)
    public String temp2(Model model) {
        return "/templates/elec/temp3";
    }

    @RequestMapping(value = "/temp3", method = RequestMethod.GET)
    public String temp3(Model model) {
        return "/templates/elec/temp3";
    }

    /**
     * 返回充电枪列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listElecGun", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listLabel(ElecGunSearch elecGunSearch) {
        TenantUser user = ShiroUtils.getSessionUser();
        elecGunSearch.setLoginName(user.getLoginName());
        /*//是否加盟商
        if(user.getMobile()!=null){
            RcOperatorExample rcOperatorExample=new RcOperatorExample();
            rcOperatorExample.createCriteria().andPhoneEqualTo(user.getMobile());
            rcOperatorExample.setOrderByClause("operator_id desc");
            RcOperator rcOperator=rcOperatorService.selectByExample(rcOperatorExample).stream().findFirst().orElseGet(()->null);
            if(rcOperator!=null){
                elecGunSearch.setOperatorId(rcOperator.getOperatorId());
            }
//            if(user.getTenantRoleId()!=null){
//                TenantRole tenantRole=tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
//                if(tenantRole.getDataAuth()!=null&&!"111".equals(tenantRole.getDataAuth().toString())){
//                    elecGunSearch.setDataAuth(String.format("%03d",tenantRole.getDataAuth()));
//                }
//            }
        }*/

        PageInfo<ElecGun> pageInfo = elecGunService.listPageByCondition(elecGunSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出充电枪列表
     */
    @ResponseBody
    @RequestMapping(value = "/exportGun", method = RequestMethod.GET)
    public TResponse export(ElecGunSearch elecGunSearch, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ExportUtils.setDefaultPaging(elecGunSearch);
            PageInfo<ElecGun> pageInfo = elecGunService.listPageByCondition(elecGunSearch);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("充电枪列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ElecGun.class).sheet("充电枪列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出充电枪列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    /**
     * 跳转增加桩群
     *
     * @return
     */
    @RequestMapping(value = "/addElecGun", method = RequestMethod.GET)
    public String addStation(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<ElecPile> piles = elecPileService.selectListPiles(user.getTenantCode());
        model.addAttribute("piles",piles);
        return "/templates/elec/addElecGun";
    }

    /**
     * 保存枪错误
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateElecGun", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateElecStation(ElecGun elecGun){
        TenantUser user = ShiroUtils.getSessionUser();
        try {
            TResponse tResponse = elecGunService.saveOrUpdateElecGun(elecGun, user.getTenantCode(), user.getLoginName());
            return tResponse;
        }catch (Exception e){
            logger.error("保存枪错误", e);
            return TResponse.FAIL("保存枪错误");
        }
    }

    /**
     * 跳转编辑桩群
     *
     * @return
     */
    @RequestMapping(value = "/editElecGun/{elecGunId}", method = RequestMethod.GET)
    public String editLabel(@PathVariable("elecGunId") Long elecGunId, Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        ElecGun info = elecGunService.selectByPrimaryKey(elecGunId);
        model.addAttribute("elecGun", info);
        List<ElecPile> piles = elecPileService.selectListPiles(user.getTenantCode());
        model.addAttribute("piles", piles);
        return "/templates/elec/editElecGun";
    }

    /**
     * 保存编辑桩群电价
     *
     * @return
     */
    @RequestMapping(value = "/deleteElecGun", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteElecLabel(Long elecGunId) {
        ElecGun info = elecGunService.selectByPrimaryKey(elecGunId);
        if (info==null){
            return TResponse.FAIL("请求错误");
        }
        elecGunService.deleteByPrimaryKey(elecGunId);
        return TResponse.SUCCESS();
    }
    /**
     * 跳转枪详情页面
     *
     * @return
     */
    @RequestMapping(value = "/detailElecGun/{elecGunId}", method = RequestMethod.GET)
    public String detailElecGun(@PathVariable("elecGunId") Long elecGunId, Model model) {
        ElecGun elecGun = elecGunService.selectByPrimaryKey(elecGunId);
        model.addAttribute("elecGun", elecGun);
        if (elecGun.getElecPileId()!=null){
            ElecPile elecPile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());
            model.addAttribute("elecPile", elecPile);
            if (elecPile.getElecStationId()!=null){
                ElecStationAndCityName elecStation = elecStationService.selectStationAndCity(elecPile.getElecStationId());
                Date operateStartTime = elecStation.getOperateStartTime();
                if (operateStartTime != null) {
                    elecStation.setOperateStartDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(operateStartTime));
                }
                model.addAttribute("elecStation", elecStation);
                List<PlatformProvince> provinces = areaService.listAllProvince();
                model.addAttribute("provinces", provinces);
                //model.addAttribute("elecGun", elecGun);
            }
            if (elecPile.getOperatorId()!=null){
                RcOperator operator = operatorService.selectByPrimaryKey(elecPile.getOperatorId());
                model.addAttribute("operator", operator);
            }
        }
        return "/templates/elec/detailElecGun";
    }


    /**
     *
     * 小程序二维码
     * @param gunNo
     * @return
     */
    @RequestMapping(value = "/genElecGunQrCode/{gunNo}", method = RequestMethod.GET)
    public String genElecGunQrCode(@PathVariable("gunNo") String gunNo, Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (user == null) {
            return null;
        }
        String url = QrCodeUtils.createCecQRCode(user.getTenantCode(), gunNo);
        model.addAttribute("qrcode", url);

        //小程序二维码生成
        String miniQrcode = QrCodeUtils.createMiniQRCode(user.getTenantCode(), gunNo);
        model.addAttribute("miniQrcode", miniQrcode);

        //新增第三方二维码
        HlhtTenantOpenfor hlhtTenantOpenfor = hlhtTenantOpenforService.selectTenantOpenforByGunNo(user.getTenantCode(), gunNo);
        if (hlhtTenantOpenfor != null) {
            String hlhtQrcode = QrCodeUtils.createCecQRCode(hlhtTenantOpenfor.getHlhtTenantCode(), gunNo);
            model.addAttribute("hlhtQrcode", hlhtQrcode);
        }


        //微信公众号网页授权
        //ElecGun elecGun = elecGunService.selectGunByGunNo(gunNo);
        //String wechatQrcode = QrCodeUtils.createWechatQRCode(user.getTenantCode(), gunNo, elecGun.getElecStationId().toString());
        //model.addAttribute("qrcodeWechat", wechatQrcode);

        return "/templates/elec/elecGunQrcode";
    }

}
